// 路由鉴权、路由守卫配置
import router from '@/router/index'
import useFinanceStore from '@/store/modules/finance'
import useMemberStore from '@/store/modules/member'
import useUserStore from '@/store/modules/user'

router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const financeStore = useFinanceStore()
    const memberStore = useMemberStore()
    // 进行判断：如果用户未登录，则只能访问登录页面，登录后无法访问登录页面
    if (localStorage.getItem('token')?.length) {

        // 因为刷新会重置userstore，所以重新获取token

        if (!userStore.token.length)
            userStore.token = (localStorage.getItem('token') as string)
        // 已登录，访问登录页面则重定向至首页
        if (to.path == '/login') {
            next('/')
        }
        else {
            // 进行判断：userStore 信息是否完整，如果不完整，那么从后台拿
            if (!memberStore.member?.length) {
                memberStore.getMembers()
            }
            if (!financeStore.expenseType?.length) {
                financeStore.getExpenseTypes()
            }
            if (!financeStore.incomeType?.length) {
                financeStore.getIncomeTypes()
            }
            next()
        }
    } else {
        // 未登录,无论访问什么页面，直接定向至login
        if (to.path === '/login') {
            next()
        }
        else {
            next('/login')
        }
    }

})
